package com.sukumar.android.sms.activity;

import java.util.ArrayList;
import java.util.LinkedHashMap;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.sukumar.android.sms.BingDetails;
import com.sukumar.android.sms.R;
import com.sukumar.android.sms.service.SMSEmailService;
import com.sukumar.android.sms.service.SmsNotifierService;

public class SMSBingActivity extends Activity {
	ListView list;
	ArrayList<BingDetails> arrBingList = new ArrayList<BingDetails>();
	ArrayList<BingDetails> selBingList = new ArrayList<BingDetails>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_layout);

		try {
			getSMSList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		list = (ListView) findViewById(R.id.list);
		ArrayAdapter<BingDetails> adapter = new ArrayAdapter<BingDetails>(this,
				R.layout.bing_list, arrBingList);
		list.setAdapter(adapter);
		if (arrBingList.size() == 1
				&& arrBingList.get(0).getBingId().equals("-9999")) {
			list.setClickable(false);
			list.setLongClickable(false);
		} else {
			registerForContextMenu(list);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.about_menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if (item.getTitle().equals("Stop alert")) {
			stopService(new Intent(getApplicationContext(),
					SmsNotifierService.class));
		} else if (item.getTitle().equals("Preferences")) {
			startActivity(new Intent(getApplicationContext(),
					SMSPreferenceActivity.class));
		} else if (item.getTitle().equals("Refresh list")) {
			arrBingList.clear();
			getSMSList();
			refreshListView();
		} else if (item.getTitle().equals("Back all")) {
			SharedPreferences myPrefs = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			boolean prefbackgroundMail = myPrefs.getBoolean(
					getText(R.string.direct_email_key).toString(), true);
			if (prefbackgroundMail) {
				int backCount = 0;
				if (arrBingList.size() > 0) {
					for (int i = 0; i < arrBingList.size(); i++) {
						try {
							sendMailAuto(arrBingList.get(i), "Back");
							backCount++;
						} catch (Exception e) {

							e.printStackTrace();
						}
					}
					Toast.makeText(getApplicationContext(),
							backCount + " bings have been backed.",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(),
							"No bings have been selected.", Toast.LENGTH_SHORT)
							.show();
				}
			} else {
				Toast.makeText(getApplicationContext(),
						"This feature needs background email to be enabled.",
						Toast.LENGTH_SHORT).show();
			}
		} else if (item.getTitle().equals("Back selected")) {
			SharedPreferences myPrefs = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			boolean prefbackgroundMail = myPrefs.getBoolean(
					getText(R.string.direct_email_key).toString(), true);
			if (prefbackgroundMail) {
				int backCount = 0;
				if (selBingList.size() > 0) {
					for (int i = 0; i < selBingList.size(); i++) {
						try {
							sendMailAuto(selBingList.get(i), "Back");
							backCount++;
						} catch (Exception e) {

							e.printStackTrace();
						}
					}
					Toast.makeText(getApplicationContext(),
							backCount + " bings have been backed.",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(),
							"No bings have been selected.", Toast.LENGTH_SHORT)
							.show();
				}
			} else {
				Toast.makeText(getApplicationContext(),
						"This feature needs background email to be enabled.",
						Toast.LENGTH_SHORT).show();
			}
		} else if (item.getTitle().equals("Delete selected")) {
			int delCount = 0;
			if (selBingList.size() > 0) {
				for (int i = 0; i < selBingList.size(); i++) {
					delCount += deleteSMS(selBingList.get(i));
				}
				refreshListView();
				Toast.makeText(getApplicationContext(),
						delCount + " messages have been deleted.",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(),
						"No bings have been selected.", Toast.LENGTH_SHORT)
						.show();
			}

		} else if (item.getTitle().equals("Delete all")) {
			int delCount = 0;
			ArrayList<BingDetails> tempList = new ArrayList<BingDetails>();
			tempList.addAll(arrBingList);
			if (tempList.size() > 0) {
				for (int i = 0; i < tempList.size(); i++) {
					delCount += deleteSMS(tempList.get(i));
				}
				refreshListView();
				Toast.makeText(getApplicationContext(),
						delCount + " messages have been deleted.",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(),
						"No bings have been selected.", Toast.LENGTH_SHORT)
						.show();
			}
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void getSMSList() {
		final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
		String WHERE_CONDITION = "body like '%BING%'";
		String SORT_ORDER = "date DESC";
		LinkedHashMap<String, BingDetails> hmBingDets;

		hmBingDets = new LinkedHashMap<String, BingDetails>();

		Cursor cur = getContentResolver().query(SMS_INBOX,
				new String[] { "address", "body" }, WHERE_CONDITION, null,
				SORT_ORDER);

		if (cur.getCount() > 0) {
			String strBingBody = "";
			BingDetails bingDets = null;
			if (cur.moveToFirst()) {
				do {
					strBingBody = cur.getString(1);
					bingDets = new BingDetails();
					bingDets.setBingId(strBingBody.substring(
							strBingBody.indexOf("<") + 1,
							strBingBody.indexOf(">")));
					bingDets.setBingFrom(cur.getString(1));
					bingDets.setBingSentTo(strBingBody.substring(strBingBody
							.indexOf(">") + 2, strBingBody.indexOf(">",
							strBingBody.indexOf(">") + 1)));
					bingDets.setBingText(strBingBody.substring(strBingBody
							.indexOf(">", strBingBody.indexOf(">") + 1) + 1));
					if (hmBingDets.containsKey(bingDets.getBingId())) {
						BingDetails oldBingDets = hmBingDets.get(bingDets
								.getBingId());
						oldBingDets.setCount(oldBingDets.getCount() + 1);
						hmBingDets.put(oldBingDets.getBingId(), oldBingDets);

					} else {
						hmBingDets.put(bingDets.getBingId(), bingDets);
					}
				} while (cur.moveToNext());
			}

			if (hmBingDets.size() > 0) {
				arrBingList.addAll(hmBingDets.values());
			}
			cur.deactivate();
			cur.close();

		} else {
			BingDetails bingDets = new BingDetails();
			bingDets.setBingId("-9999");
			arrBingList.add(bingDets);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.list) {
			menu.setHeaderTitle(R.string.long_click_action);
			String[] menuItems = getResources().getStringArray(
					R.array.context_menu);
			for (int i = 0; i < menuItems.length; i++) {
				menu.add(Menu.NONE, i, i, menuItems[i]);
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();
		BingDetails selBingDet = arrBingList.get(info.position);
		switch (menuItemIndex) {
		case 0:
			sendEmail(selBingDet, "Back");
			break;
		case 1:
			int deleted = deleteSMS(selBingDet);
			refreshListView();
			Toast.makeText(getApplicationContext(),
					deleted + " messages ave been deleted.", Toast.LENGTH_SHORT)
					.show();
			break;
		case 2:
			selBingList.add(selBingDet);
			break;
		}
		return true;
	}

	private int deleteSMS(BingDetails bingDetails) {
		int no_of_messages_deleted = 0;
		no_of_messages_deleted = this.getContentResolver().delete(
				Uri.parse("content://sms"),
				"body like '%" + bingDetails.getBingId() + "%'", null);
		arrBingList.remove(bingDetails);
		if (arrBingList.size() == 0) {
			BingDetails bingDets = new BingDetails();
			bingDets.setBingId("-9999");
			arrBingList.add(bingDets);
		}
		return no_of_messages_deleted;
	}

	private void refreshListView() {
		list.setAdapter(new ArrayAdapter<BingDetails>(this, R.layout.bing_list,
				arrBingList));
		if (arrBingList.size() == 1
				&& arrBingList.get(0).getBingId().equals("-9999")) {
			list.setClickable(false);
			list.setLongClickable(false);
			unregisterForContextMenu(list);
		} else {
			registerForContextMenu(list);
		}

	}

	private void sendEmail(BingDetails bingDets, String action) {
		SharedPreferences myPrefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		boolean prefbackgroundMail = myPrefs.getBoolean(
				getText(R.string.direct_email_key).toString(), true);
		if (!prefbackgroundMail) {
			final Intent emailIntent = new Intent(
					android.content.Intent.ACTION_SEND);
			emailIntent.setType("plain/text");
			emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
					new String[] { "bingmail-gl@nomura.com" });
			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, action
					+ " " + bingDets.getBingId());
			emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "The BING "
					+ bingDets + " is backed.");
			startActivity(Intent.createChooser(emailIntent, "Send mail..."));
		} else {
			try {
				sendMailAuto(bingDets, action);
			} catch (Exception e) {
				e.printStackTrace();

				Toast.makeText(getApplicationContext(), e.toString(),
						Toast.LENGTH_SHORT).show();

			}
		}
	}

	private void sendMailAuto(BingDetails bingDets, String action) {
		Intent mailService = new Intent(getApplicationContext(),
				SMSEmailService.class);
		mailService.putExtra("bingId", bingDets.getBingId());
		mailService.putExtra("action", action);
		startService(mailService);
	}

}
